package com.tiny.tinyweb.core.utils;

import java.util.List;
/**
 * 字符串数组排序的工具类
 * @author goood-like
 *
 */
public class SortUtil {
	/**
	 *  按照字符串快速排序（数字优先于含有非数字的字符串）
	 * @param strArray
	 * @return
	 */
	public static String[] getSortedArray(String[] strArray) {
		try {
			QuickSort(0, strArray.length - 1,strArray);
		} catch (NullPointerException e) {
			System.out.print("null array!");
		}
		return strArray;
	}
	/**
	 *  按照字符串快速排序（数字优先于含有非数字的字符串）
	 * @param strArray
	 * @return
	 */
	public static List<String> getSortedList(String[] strArray) {
		try {
			QuickSort(0, strArray.length - 1,strArray);
		} catch (NullPointerException e) {
			System.out.print("null array!");
		}
		return java.util.Arrays.asList(strArray);
	}
	
	private static boolean CheckNum(String str) {
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) > '9' || str.charAt(i) < '0')
				return false;
		}
		return true;
	}

	private static boolean CompareTwoStrings(String a, String b) {
		if (CheckNum(a) && CheckNum(b)) {
			if (a.length() > b.length()) {
				int numOfZeroAddedOfB = a.length() - b.length();
				StringBuilder zeros_of_b = new StringBuilder();
				for (int i = 0; i < numOfZeroAddedOfB; i++) {
					zeros_of_b.append("0");
				}
				b = zeros_of_b.toString() + b;
			} else {
				int numOfZeroAddedOfA = b.length() - a.length();
				StringBuilder zeros_of_a = new StringBuilder();
				for (int i = 0; i < numOfZeroAddedOfA; i++) {
					zeros_of_a.append("0");
				}
				a = zeros_of_a.toString() + a;
			}
		}
		return a.compareTo(b) > 0 ? true : false;
	}
	
	private static int Partition(int start, int end,String[] strArray) {
		String baseValue = strArray[start];
		int basePos = start;
		for (int i = start + 1; i <= end; i++) {
			if (CompareTwoStrings(baseValue, strArray[i])) {
				basePos++;
				Swap(basePos, i,strArray);
			}
		}
		Swap(start, basePos,strArray);
		return basePos;
	}

	private static void QuickSort(int start, int end,String[] strArray) {
		if (start < end) {
			int basePos = Partition(start, end,strArray);
			QuickSort(start, basePos - 1,strArray);
			QuickSort(basePos + 1, end,strArray);
		}
	}

	private static void Swap(int pos1, int pos2,String[] strArray) {
		String tempValue = strArray[pos1];
		strArray[pos1] = strArray[pos2];
		strArray[pos2] = tempValue;
	}

	
	
}
